﻿using System;
using System.IO;
using System.Security.Cryptography;
using System.Web.Security;

namespace ConfExpert.Utility.Crypto
{
    public static class SaltedHashing
    {
        private const int SaltByteSize = 10;    //16 idi!

        public static string[] GetHash(string password)
        {
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            byte[] buff = new byte[SaltByteSize];
            rng.GetBytes(buff);
            string salt = Convert.ToBase64String(buff).Substring(0, 10);
            return new string[] { salt, FormsAuthentication.HashPasswordForStoringInConfigFile(salt + password, "SHA1") };
        }
    }

    public static class MD5
    {
        public static string GetHashFromFile(string fileName)
        { 
            
            FileStream fs = new FileStream(fileName, FileMode.Open);
            System.Security.Cryptography.MD5 md5 = new MD5CryptoServiceProvider();
            byte[] hash = md5.ComputeHash(fs);
            fs.Close();

            return GetHex(hash);
        }

        public static string GetHash(byte[] content)
        {
            System.Security.Cryptography.MD5 md5 = new MD5CryptoServiceProvider();
            byte[] hash = md5.ComputeHash(content);

            return GetHex(hash);
        }

        private static string GetHex(byte[] hash)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            foreach (byte hex in hash)
                sb.Append(hex.ToString("x2"));

            return sb.ToString();
        }
    }
}